class UserInterface:
    def __init__(self, search_engine):
        self.search_engine = search_engine

    def start(self):
        """启动命令行用户界面"""
        print("欢迎使用阿里电商搜索系统!")
        while True:
            print("\n请选择操作:")
            print("1. 搜索商品")
            print("2. 查看搜索建议")
            print("3. 退出")

            choice = input("请输入选项: ")

            if choice == "1":
                self._search_menu()
            elif choice == "2":
                self._suggestion_menu()
            elif choice == "3":
                print("感谢使用，再见!")
                break
            else:
                print("无效选项，请重新输入。")

    def _search_menu(self):
        """搜索功能子菜单"""
        query = input("请输入搜索关键词: ")

        # 可选的过滤条件
        min_price = self._get_numeric_input("最低价格 (可选，直接回车跳过): ", allow_empty=True)
        max_price = self._get_numeric_input("最高价格 (可选，直接回车跳过): ", allow_empty=True)
        category = input("商品分类 (可选，直接回车跳过): ")
        brand = input("品牌 (可选，直接回车跳过): ")

        # 排序选项
        print("\n排序方式:")
        print("1. 按相关性")
        print("2. 价格从低到高")
        print("3. 价格从高到低")
        print("4. 按评分")
        print("5. 按销量")
        sort_choice = input("请选择排序方式 (默认1): ")

        sort_map = {
            "1": "relevance",
            "2": "price_asc",
            "3": "price_desc",
            "4": "rating",
            "5": "sales"
        }
        sort_by = sort_map.get(sort_choice, "relevance")

        # 执行搜索
        results = self.search_engine.search(
            query,
            sort_by=sort_by,
            min_price=min_price,
            max_price=max_price,
            category=category,
            brand=brand
        )

        # 显示结果
        self._display_search_results(results)

    def _suggestion_menu(self):
        """搜索建议子菜单"""
        prefix = input("请输入搜索前缀: ")
        suggestions = self.search_engine.get_suggestions(prefix)

        print("\n搜索建议:")
        for i, suggestion in enumerate(suggestions, 1):
            print(f"{i}. {suggestion}")

    def _display_search_results(self, results):
        """显示搜索结果"""
        if not results:
            print("\n没有找到匹配的商品。")
            return

        print(f"\n找到 {len(results)} 个商品:")
        for i, product in enumerate(results[:10], 1):  # 只显示前10个结果
            price_display = f"{product.price:.2f}"
            if product.is_promoted:
                price_display += f" (促销: {product.get_discounted_price():.2f})"

            print(f"\n{i}. {product.name}")
            print(f"   品牌: {product.brand}")
            print(f"   分类: {product.category}")
            print(f"   价格: ¥{price_display}")
            print(f"   评分: {product.rating}/5.0")
            print(f"   销量: {product.sales_volume}")
            print(f"   简介: {product.description[:50]}...")

    def _get_numeric_input(self, prompt, allow_empty=False):
        """获取数字输入，处理非数字情况"""
        while True:
            value = input(prompt)
            if allow_empty and not value:
                return None
            try:
                return float(value)
            except ValueError:
                print("请输入有效的数字。")